package com.example.algorithm.aPrimarySort;

import com.alibaba.fastjson.JSON;

/**
 * @author: dangwen
 * @createDate: 2022/4/25
 * 归并排序
 */
public class MergeSort {
    public static void main(String[] args) {
        int[] nums = {4,5,1,2,3,7,8};
        mergeSort(nums, 0, nums.length - 1, new int[nums.length]);
        System.out.println(JSON.toJSONString(nums));
    }

    private static void mergeSort(int[] nums, int left, int right, int[] temps) {
        if (left >= right){
            return;
        }
        int mid = left + ((right - left) >> 1);
        mergeSort(nums, left, mid, temps);
        mergeSort(nums, mid + 1, right, temps);

        merge(nums, left, mid, right, temps);
    }

    private static void merge(int[] nums, int left, int mid, int right, int[] temps) {
        for (int i = left; i <= right; i++) {
            temps[i] = nums[i];
        }

        int i = left;
        int j = mid + 1;
        for (int k = left; k <= right; k++){
            if (i == mid + 1){
                nums[k] = temps[j++];
            } else if (j == right + 1){
                nums[k] = temps[i++];
            } else if (temps[i] < temps[j]){
                nums[k] = temps[i++];
            } else {
                nums[k] = temps[j++];
            }
        }
    }



}
